<template>
<div>
	<content_top title="人员分摊表" isAccounts="1"></content_top>
	<div class="g_box">
		<div class="g_head">
			<h3>横向表头</h3>
			<div class="g_box_right">
				<ButtonGroup class="g_act_box">
					<!-- <Button @click="prev_use('a_xlist')">延用上次设定</Button> -->
					<Button @click="keep_data('a_xlist')">保存表格</Button>
				</ButtonGroup>
				<div class="g_other">
					<a @click="handleClearHTable('a_xlist')">全部清除</a>
				</div>
			</div>
		</div>

		<!-- 部门、规则 -->
		<bumen_item ref="a_xlist"></bumen_item>

	</div>

	<div class="g_box">
		<div class="g_head">
			<h3>纵向表头</h3>
			<div class="g_box_right">
				<ButtonGroup class="g_act_box">
					<!-- <Button @click="prev_use('a_ylist')">延用上次设定</Button> -->
					<Button @click="keep_data('a_ylist')">保存表格</Button>
				</ButtonGroup>
				<div class="g_other">
					<a @click="handleClearHTable('a_ylist')">全部清除</a>
				</div>
			</div>
		</div>

		<div class="g_box_con" style="padding:20px;">
			<Row>
				<Col span="8">
					<Form  :label-width="90" style="width: 100%" inline>
						<FormItem label="部门：">
							<bumen_filter v-model="filter.bumen" field="name" style="width:150px;"></bumen_filter>
						</FormItem>
					</Form>
				</Col>
			</Row>
		</div>

		<!-- 部门、科目 -->
		<kemu_item ref="a_ylist"></kemu_item>
		
	</div>
	<!-- 表格 -->
	<div class="g_box">
    
      <div class="g_head">
        <h3>
			数据列表
			<DatePicker :value="filter.date_month" type="month" placeholder="选择月份" style="width: 180px;margin-left: 20px;" @on-change="month_change"></DatePicker>
		</h3>
        <div class="g_box_right">
          <ButtonGroup class="g_act_box">
          	
            <Button @click="export_data">导出表格</Button>
            <Button @click="query">刷新表格</Button>
            <Button @click="keep_num_data">保存表格</Button>
          </ButtonGroup>
        </div>
      </div>
      <div class="g_box_con">
        <Table :columns="Columns" :data="list"  :border="true" >
			<template slot-scope="{ row, index }" slot="money">
				<input 
					type="text"
					v-model="row.money"
					:readonly="!row.isEdit"
					placeholder="双击输入"
					@dblclick="handleCanEdit(index)"
					@blur="handleInputBlur(index)"
					style="width:100%;padding:5px;text-align:center;border: 0 ;outline: none;"
				/>
			</template>
		</Table>
		<div style="font-size: 14px;overflow: hidden;padding: 10px;">
			<div style="float:left;">
				<Button type="success" @click="save_data">确定分摊</Button>
			</div>
		</div>
      </div>
  </div>
</div>
</template>

<script>
import bumen_item from './bumen_item';
import kemu_item from './kemu_item';
import Wcore from '@/libs/common';
import bumen_filter from '@/themes/components/bumen_filter';

export default {
	name: 'share_member_list',
	inject:['reload'],
    data () {
		let self = this;
        return {
			filter:{
				date_month:localStorage.account_balance?localStorage.account_balance:new Date().Format('yyyy-MM'),
				bumen:""
			},
			Columns:[],
			list:[],
			inputVals:{},
			custemVals:{} //自定义输入的数
        };
	},
	components:{
		bumen_item,
		kemu_item,
		bumen_filter,
	},
	created(){
		/*var self = this;
		setTimeout(function(){ 
			self.load_data();
		}, 1000);*/
	},
    computed: {
       
    },
	methods:{
		month_change(date){
			this.filter.date_month = date;
		},
		//延用上次
		prev_use(name){
			var data = Wcore.getData(name);
			if(!data){
				return ;
			}
			this.$refs[name].set_data(data);
		},
		keep_data(name){
			var data = this.$refs[name].get_data();
			Wcore.setData(name,data);
			this.$Message.info('成功保存表格');
		},
		keep_num_data(){
			//if(Object.keys(this.custemVals).length != 0 && Object.keys(this.inputVals).length != 0){}
			if(Object.keys(this.inputVals).length != 0){//存在人员统计百分数时
				Wcore.setData('num_list',this.inputVals);
			}
			if(Object.keys(this.custemVals).length != 0){//存在人员统计百分数时
				Wcore.setData('cus_list',this.custemVals);
			}
			this.$Message.info('成功保存表格');
		},
		get_num_data(name){
			var data = Wcore.getData(name);
			if(!data){
				return {};
			}
			return this._getData(data);
		},
		handleClearHTable(name) {
			Wcore.setData(name,false);
			this.reload();
		},
		query(){
			this.inputVals = {};
			this.custemVals = {};
			this.load_data();
		},
		load_data(){

			var self = this;
			
			var xdata = this.$refs['a_xlist'].get_data();
			var ydata = this.$refs['a_ylist'].get_data();
			
			var postdata = {
				xdata:xdata,
				ydata:ydata,
				f:this.filter
			};
			Whttp.load('Accounting/ShareMember/new_get_data',postdata,function(result){//console.log(result);return false;
				self.inputVals = self.get_num_data('num_list');
				self.custemVals = self.get_num_data('cus_list');
				/*if(Object.keys(self.inputVals).length != 0){//存在人员统计百分数时
					self.inputVals = self.get_num_data('num_list');
				}
				if(Object.keys(self.custemVals).length != 0){//存在人员统计百分数时
					self.custemVals = self.get_num_data('cus_list');
				}*/
				
				self.set_Columns(result.xlist);
			
				var list = [{
					name:'人员统计',
					is_edit:1,
					total:0,
					custotal:0
				},{
					name:ydata.info.name,
					is_edit:1,
					total:ydata.info.exchange_rate
				}];
			
				for(var i=0;i<result.ylist.length;i++){
					list.push(result.ylist[i]);
				}
				
				self.list = list;
				
				self.get_input_total();
				self.get_subject_total();
			});
		},
		set_Columns(list){
			this.Columns = [];
			
			for(var i=0;i<list.length;i++){
				var ls_colnmn = {
					title: list[i].value,
					key: list[i].key,
					align: 'center',
					width: 150,
				};
				if(i>=2){
					ls_colnmn['render'] = this.mrender;
				}
				
				if(list[i].children){
					var childrens = list[i].children;
					var ls_child = [];
					for(var j=0;j<childrens.length;j++){
						ls_child.push({
							title: childrens[j].value,
							key: childrens[j].key,
							align: 'center',
							width: 150,
							render: this.mrender
						});
					}
					ls_colnmn.children = ls_child;
				}
				this.Columns.push(ls_colnmn);
			}//console.log(this.Columns);return false;

		},
		// 双击输入
		handleCanEdit(index) {
			this.list[index].isEdit = true;
		},
		handleInputBlur(index,val) {
			console.log(val);
			this.list[index].isEdit = false;
		},
		mrender(h, params){
			var self = this;
			if(!params.row.is_edit){
				return h('div',params.row[params.column.key]);
			}
			
			if(params.row._index != 1){			
				var valu = self.inputVals[params.column.key]?self.inputVals[params.column.key]:0;
			}else{
				var valu = self.custemVals[params.column.key]?self.custemVals[params.column.key]:0;
			}

			return h('InputNumber',{
				props:{
					value:valu,
					//value:self.inputVals[params.row.key]?self.inputVals[params.row.key]:0,
					max:100,
					min:0,
					step:1
				},
				attrs:{
					placeholder:'输入',
					
				},
				style:{
					textAlign:'center'
				},
				on:{
					'on-change':(val)=>{
						//self.inputVals[params.row.key] = val;
						
						if(params.row._index != 1){
							
							this.inputVals[params.column.key] = val;
							this.get_input_total();
							
						}else{
							this.custemVals[params.column.key] = val;
							this.get_custem_total();
						}
						
						this.get_subject_total();

					}
				}
			});
		},
		get_custem_total(){
			var total = 0;
			for(var i in this.custemVals){
				total += parseFloat(this.custemVals[i]);
			}
			
			this.list[0].custotal = total.toFixed(2);//console.log(this.list);return false;
		},
		get_input_total(){
			var total = 0;
			for(var i in this.inputVals){
				total += parseFloat(this.inputVals[i]);
			}
			
			this.list[0].total = total.toFixed(2);
		},
		get_subject_total(){
			var total = 0;
			for(var i in this.inputVals){
				total += parseFloat(this.inputVals[i]);
			}

			var c_total = 0;
			for(var i in this.custemVals){
				c_total += parseFloat(this.custemVals[i]);
			}
			
			for(var i=0;i<this.list.length;i++){
				if(i<2){
					continue;
				}
				var subject_total = this.list[i].total;

				//如果是最后一行，即费用分摊那行时
				if(i==this.list.length-1){

					var cus_total = this.list[i].cus_total?this.list[i].cus_total:0;
					//如果存在自定义数据，并且第一行数据也存在
					if(Object.keys(this.custemVals).length != 0 && Object.keys(this.inputVals).length != 0){
						
						for(var k in this.inputVals){
					
							if(subject_total<=0){
								var ls_val = 0;
							}
							else{
								
								if(this.custemVals[k]){
									ls_val = parseFloat(((subject_total-cus_total)/total)*this.inputVals[k])+parseFloat((cus_total/c_total)*this.custemVals[k]);
								}else{
									ls_val = parseFloat(((subject_total-cus_total)/total)*this.inputVals[k]);
								}
							}
							
							this.list[i][k] = this.toFixed(ls_val);
						}
					}
					//如果只有自定义数据时
					else if(Object.keys(this.custemVals).length != 0 && Object.keys(this.inputVals).length == 0){

						for(var k in this.custemVals){
					
							if(subject_total<=0){
								var ls_val = 0;
							}
							else{
								ls_val = parseFloat((cus_total/c_total)*this.custemVals[k]);
							}
							
							this.list[i][k] = this.toFixed(ls_val);
						}

					}
					//如果只有第一行数据时
					else if(Object.keys(this.custemVals).length == 0 && Object.keys(this.inputVals).length != 0){

						for(var k in this.inputVals){
					
							if(subject_total<=0){
								var ls_val = 0;
							}
							else{
								ls_val = parseFloat(((subject_total-cus_total)/total)*this.inputVals[k]);
							}
							
							this.list[i][k] = this.toFixed(ls_val);
						}

					}

				}else{

					for(var k in this.inputVals){
					
						if(subject_total<=0){
							var ls_val = 0;
						}
						else{
							var ls_val = parseFloat((subject_total/total)*this.inputVals[k]);
						}
						
						this.list[i][k] = this.toFixed(ls_val);
					}

				}
			}
			
		},
		toFixed(num,pos){
			var pos = pos || 2;
			var ws = 1;
			num = parseFloat(num);
			for(var i=0;i<pos;i++){
				ws *= 10;
			}
			return Math.floor(num * ws) / ws;
		},
		export_data(){
			var self = this;
			
			var xdata = this.$refs['a_xlist'].get_data();
			var ydata = this.$refs['a_ylist'].get_data();
			
			var postdata = {
				xdata:xdata,
				ydata:ydata,
				list:this.list,
				f:this.filter,
				exps:this.inputVals,
				cusexps:this.custemVals
			};
			Whttp.load('Accounting/ShareMember/new_export_data',postdata,function(result){//console.log(result);return false;
				window.open(result);
			})
		},
		//确认分摊，写入团队损益表
		save_data(){
			var self = this;
			if(Object.keys(this.inputVals).length == 0){
				alert('请先分摊，再确认');
				return ;
			}

			var xdata = this.$refs['a_xlist'].get_data();
			var ydata = this.$refs['a_ylist'].get_data();
			
			var postdata = {
				xdata:xdata,
				list:this.list,
				date_month:this.filter.date_month,
				mtype:1
			};
			//console.log(postdata);return false;
			Whttp.load('Accounting/TeamCash/share_save',postdata,function(result){
				self.$Message.info('成功分摊');
			});
		}
	}
};
</script>
<style scoped>
.price{
	color: red;
    margin: 0 5px;
}
.kemu_list .ivu-col-span-4{
	font-size: 18px;
	margin-bottom:8px;
}
</style>